package top.roadvast.sort.sort_obj;

import java.util.ArrayList;
import java.util.Collections;

public class ComparableDemo {

    public void demoForComparable() {
        CutePig pig1 = new CutePig("猪聪明", 18);  // 第一个对象
        CutePig pig2 = new CutePig("猪可爱", 12);  // 第二个对象
        CutePig pig3 = new CutePig("猪能干", 16);  // 第三个对象
        ArrayList<CutePig> pigList = new ArrayList<>();
        pigList.add(pig1);
        pigList.add(pig2);
        pigList.add(pig3);
        Collections.sort(pigList);
        System.out.println("按年龄排序(升序)后结果如下");
        for (CutePig pig : pigList) {
            System.out.println(pig.toString());
        }
    }

    public static void main(String[] args) {
        ComparableDemo obj = new ComparableDemo();
        obj.demoForComparable();
    }

    class CutePig implements Comparable<CutePig> {
        String name;
        int age;

        public CutePig(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "name is " + this.name + "; age is " + this.age;
        }

        @Override
        public int compareTo(CutePig other) {
            if (this == other) {
                return 0;
            }
            return this.age - other.age;
        }
    }
}